package edu.hawaii.myisern.action;

import net.sourceforge.stripes.controller.Interceptor;
import net.sourceforge.stripes.controller.Intercepts;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.controller.ExecutionContext;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.ActionBeanContext;

/**
 * Interceptor that checks to make sure user is logged in whenever he accesses a page.
 * @author Ben
 *
 */
@Intercepts(LifecycleStage.ActionBeanResolution)
public class LoginInterceptor implements Interceptor {
  
  /**
   * Method that runs when user accesses a page.
   * @return Resolution to page to be accessed or login page if they are not logged in.
   * @param interceptContext the context under which the page access is being made.
   * @throws Exception if error occurs.
   */
  public Resolution intercept(ExecutionContext interceptContext) throws Exception {
    Resolution resolution = interceptContext.proceed();
    

      if (isLoggedIn(interceptContext.getActionBeanContext())) {
          return resolution;
      }
      else if (interceptContext.getActionBean().getClass().equals(LoginActionBean.class)) {
          return resolution;
      }
      else {
          return new RedirectResolution("/login.jsp");
      }
  }

  /** Returns true if the user is logged in. 
   *  @return boolean true if logged in.
   *  @param context to determine if context is logged in.
   */
  protected boolean isLoggedIn(ActionBeanContext context) { 
      return ((MyIsernContext) context).getLoggedIn();
  }
}
